<script setup lang="ts">
import PauseCircleOutlined from "@ant-design/icons-vue/PauseCircleOutlined";
import PlayCircleOutlined from "@ant-design/icons-vue/PlayCircleOutlined";
import {message} from "ant-design-vue";
import dayjs, {Dayjs} from "dayjs";
import {sendMessage, onMessage} from "webext-bridge/content-script";
import RefreshButton from "~/contentScripts/views/wxt/components/RefreshButton.vue";
import {WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";
// 天气地域优化
const props = defineProps({
  rows: {
    type: Array,
    default: () => []
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
});
const loading = ref(false);
const updateTime = ref<Dayjs>(dayjs());
const weatherData = ref<any>({});
const loadWeather = () => {
  loading.value = true;
  message.loading({
    content: '正在加载天气数据...',
    key: 'weather',
    duration: 0
  });
  setTimeout(() => {
    sendMessage<string>('fetch', {url: '\x68\x74\x74\x70\x73\x3a\x2f\x2f\x61\x73\x73\x65\x74\x73\x2e\x64\x69\x61\x6e\x74\x6f\x75\x73\x68\x69\x2e\x63\x6f\x6d\x2f\x76\x65\x6e\x64\x6f\x72\x73\x2f\x77\x65\x61\x74\x68\x65\x72\x2f\x69\x6e\x64\x65\x78\x2e\x6a\x73\x6f\x6e'}).then((res) => {
      message.destroy('weather');
      updateTime.value = dayjs();
      weatherData.value = JSON.parse(res);
      calcDataSource();
    }).catch(() => {
      message.destroy('weather');
      loading.value = false;
    });
  }, 0);
}
const areas = ref<any[]>([]);
WxtUtils.getAreaCodeConfig(props.bizCode).then(res => {
  areas.value = res;
})
const handle = () => {
  if (props.rows.length == 0) {
    message.error("请选择需要批量处理的数据！");
    return;
  }
  visible.value = true;
  nextTick(() => {
    loadWeather();
  })
}
const dataSource = ref<any[]>([]);
const calcDataSource = () => {
  let data: any[] = [];
  const getItem = (item: any, area: any, weather: any, status: Boolean, index: number): {
    index: number, status: Boolean, province: string, city: string, campaignId: number,
    cityId: string, provinceId: string,
    campaignName: string,
    // 天气
    todayDayWeather: string,
    todayDayTemperature: string,
    todayDayWind: string,
    todayNightWeather: string,
    todayNightTemperature: string,
    todayNightWind: string,

    tomorrowDayWeather: string,
    tomorrowDayTemperature: string,
    tomorrowDayWind: string,
    tomorrowNightWeather: string,
    tomorrowNightTemperature: string,
    tomorrowNightWind: string,

    afterTomorrowDayWeather: string,
    afterTomorrowDayTemperature: string,
    afterTomorrowDayWind: string,
    afterTomorrowNightWeather: string,
    afterTomorrowNightTemperature: string,
    afterTomorrowNightWind: string,
  } => {
    return {
      index: index,
      status: status,
      province: area.provinceName,
      campaignId: item.campaignId,
      city: area.name,
      cityId: area.id,
      provinceId: area.provinceId,
      campaignName: item.campaignName,
      todayDayWeather: weather ? weather[0].textDay || '' : null,
      todayDayTemperature: weather ? weather[0].tempMax || '' : null,
      todayDayWind: weather ? weather[0].windScaleDay || '' : null,
      todayNightWeather: weather ? weather[0].textNight || '' : null,
      todayNightTemperature: weather ? weather[0].tempMin || '' : null,
      todayNightWind: weather ? weather[0].windScaleNight || '' : null,

      tomorrowDayWeather: weather ? weather[1].textDay || '' : null,
      tomorrowDayTemperature: weather ? weather[1].tempMax || '' : null,
      tomorrowDayWind: weather ? weather[1].windScaleDay || '' : null,
      tomorrowNightWeather: weather ? weather[1].textNight || '' : null,
      tomorrowNightTemperature: weather ? weather[1].tempMin || '' : null,
      tomorrowNightWind: weather ? weather[1].windScaleNight || '' : null,

      afterTomorrowDayWeather: weather ? weather[2].textDay || '' : null,
      afterTomorrowDayTemperature: weather ? weather[2].tempMax || '' : null,
      afterTomorrowDayWind: weather ? weather[2].windScaleDay || '' : null,
      afterTomorrowNightWeather: weather ? weather[2].textNight || '' : null,
      afterTomorrowNightTemperature: weather ? weather[2].tempMin || '' : null,
      afterTomorrowNightWind: weather ? weather[2].windScaleNight || '' : null,
    }
  }
  props.rows?.forEach((item: any) => {
    areas.value.forEach((area: any) => {
      let status = true;
      if (!item.launchAreaStrList.includes(String(area.id))) {
        status = false;
      }
      data.push(getItem(item, area, weatherData.value[area.name] || null, status, data.length + 1));
    })
  });
  // console.log(data);
  dataSource.value = data;
  loading.value = false;
}
const emit = defineEmits([
  "refresh",
]);
const visible = ref(false);
const columns = [
  {
    title: '#',
    dataIndex: 'index',
    width: 60,
    fixed: 'left',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 60,
    fixed: 'left',
    dataType: 'custom',
    slot: 'status',
    customRender: (text: any, record: any) => {
      return text ? '正在推广' : '暂停推广';
    }
  },
  {
    title: '省份',
    dataIndex: 'province',
    width: 120,
    fixed: 'left',
  },
  {
    title: '城市',
    dataIndex: 'city',
    width: 140,
    fixed: 'left',
  },
  {
    title: '计划名称',
    dataIndex: 'campaignName',
    width: 160,
    fixed: 'left',
  },
  {
    title: '今天',
    children: [
      {
        title: '白天天气',
        dataIndex: 'todayDayWeather',
        width: 100,
      },
      {
        title: '白天温度',
        dataIndex: 'todayDayTemperature',
        width: 100,
      },
      {
        title: '白天风速',
        dataIndex: 'todayDayWind',
        width: 100,
      },
      {
        title: '夜间天气',
        dataIndex: 'todayNightWeather',
        width: 100,
      },
      {
        title: '夜间温度',
        dataIndex: 'todayNightTemperature',
        width: 100,
      },
      {
        title: '夜间风速',
        dataIndex: 'todayNightWind',
        width: 100,
      }
    ]
  },
  {
    title: '明天',
    children: [
      {
        title: '白天天气',
        dataIndex: 'tomorrowDayWeather',
        width: 100,
      },
      {
        title: '白天温度',
        dataIndex: 'tomorrowDayTemperature',
        width: 100,
      },
      {
        title: '白天风速',
        dataIndex: 'tomorrowDayWind',
        width: 100,
      },
      {
        title: '夜间天气',
        dataIndex: 'tomorrowNightWeather',
        width: 100,
      },
      {
        title: '夜间温度',
        dataIndex: 'tomorrowNightTemperature',
        width: 100,
      },
      {
        title: '夜间风速',
        dataIndex: 'tomorrowNightWind',
        width: 100,
      }
    ]
  },
  {
    title: '后天',
    children: [
      {
        title: '白天天气',
        dataIndex: 'afterTomorrowDayWeather',
        width: 100,
      },
      {
        title: '白天温度',
        dataIndex: 'afterTomorrowDayTemperature',
        width: 100,
      },
      {
        title: '白天风速',
        dataIndex: 'afterTomorrowDayWind',
        width: 100,
      },
      {
        title: '夜间天气',
        dataIndex: 'afterTomorrowNightWeather',
        width: 100,
      },
      {
        title: '夜间温度',
        dataIndex: 'afterTomorrowNightTemperature',
        width: 100,
      },
      {
        title: '夜间风速',
        dataIndex: 'afterTomorrowNightWind',
        width: 100,
      }
    ]
  }
]
const changeStatus = (e: any) => {
  if (selectedRows.value.length === 0) {
    message.error("请选择需要批量处理的数据！");
    return;
  }
  modify(selectedRows.value, e.key === 'start');
}
const tableBox = ref<any>(null);
const tableHeight = ref<number>(0);
const calcTableHeight = () => {
  if (tableBox.value) {
    const height = tableBox.value.clientHeight;
    tableHeight.value = height - 140;
  }
  return 0;
}
onMounted(() => {
  window.addEventListener('resize', calcTableHeight);
})
onUnmounted(() => {
  window.removeEventListener('resize', calcTableHeight);
})
watch(() => tableBox.value, (v) => {
  if (v) {
    calcTableHeight();
  }
})
const modify = (rows: any, status: undefined | boolean = undefined) => {
  nextTick(() => {
    let campaignIds: number[] = rows.map((r: any) => r.campaignId);
    // 对campaignIds进行去重
    const uniqueIds: any = {};  // 用于存储唯一的 ID
    campaignIds = campaignIds.reduce((result: number[], obj: number) => {
      if (!uniqueIds[obj]) {  // 如果 ID 在 uniqueIds 中不存在
        uniqueIds[obj] = true; // 将 ID 添加到 uniqueIds 中
        result.push(obj); // 将对象添加到结果数组中
      }
      return result;
    }, []);
    const getLaunchAreaStrList = (campaignId: number) => {
      const launchAreaStrList: string[] = [];
      const items = rows.filter((r: any) => r.campaignId === campaignId);
      items.forEach((item: any) => {
        if (typeof item.status === 'undefined') { // 单项修改 未定义状态 按照当前状态判断是否设置开启
          if (item.status) {
            launchAreaStrList.push(item.cityId);
          }
        } else {
          if (status) {
            launchAreaStrList.push(item.cityId);
            dataSource.value.find((area) => area.cityId == item.cityId).status = true;
          } else {
            dataSource.value.find((area) => area.cityId == item.cityId).status = false;
          }
        }
      })
      return launchAreaStrList;
    }
    WxtUtils.advancedBatchUpdate([
      ...campaignIds.map((campaignId: number) => {
        return {
          campaignId,
          launchAreaStrList: getLaunchAreaStrList(campaignId),
        }
      }),
    ], props.bizCode).then(res => {
      // visible.value = false;
      if (res.data.info.ok !== true) {
        message.error(res.data.info.message)
        return;
      }
      message.success("操作成功！");
    }).finally(() => {
      emit('refresh');
    });
  })
}
const selectedRows = ref<any[]>([]);
</script>

<template>
  <slot>
    <a-button size="small" type="primary" ghost @click="handle">天气地域优化</a-button>
  </slot>
  <wxt-modal width="95%" title="天气地域优化" v-model:visible="visible">
    <div style="height: calc(100vh - 105px);" ref="tableBox">
      <base-table table-name="天气地域优化" selection v-model:selected-rows="selectedRows" row-key="cityId"
                  :loading="loading" :scroll="{
      x:'100%',
      y: tableHeight
    }" :columns="columns" :dataSource="dataSource" rowKey="index" size="small" bordered pagination
      >
        <template #toolbar>
          <a-space>
            <a-dropdown trigger="click">
              <template #overlay>
                <a-menu @click="changeStatus">
                  <a-menu-item key="start">
                    <PlayCircleOutlined :style="{
      color: '#1677ff'
    }"
                    />
                    正在推广
                  </a-menu-item>
                  <a-menu-item key="pause">
                    <PauseCircleOutlined :style="{
      color: '#ff4d4f'
    }"
                    />
                    暂停推广
                  </a-menu-item>
                </a-menu>
              </template>
              <slot>
                <a-button size="small" type="primary">批量推广状态</a-button>
              </slot>
            </a-dropdown>
            <RefreshButton :loading="loading" @refresh="loadWeather"/>
            <span>
              更新时间：{{ updateTime.format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </a-space>
        </template>
        <template #status="row">
          <a-switch size="small" :checked="row.status" @change="()=>{
            dataSource.find((area)=>area.cityId==row.cityId).status=!row.status;
            nextTick(()=>modify([row]));
          }"
          />
        </template>
      </base-table>
    </div>
  </wxt-modal>
</template>

<style scoped>

</style>
